package com.zhb.cloud.config;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName: ElasticsearchConfig
 * @author: zhb
 * @date: 2017年7月27日 下午2:27:57
 * @Description: es 核心配置
 *
 */
@Configuration
public class ESConfig {
	private static final Logger logger = LoggerFactory.getLogger(ESConfig.class);
	@Value("${elasticsearch.cluster.name}")
	private String clusterName;
	@Value("${elasticsearch.cluster.nodes}")
	private String nodes;
	@Value("${elasticsearch.cluster.port}")
	private Integer port;

	public @Bean TransportClient transportClient() throws UnknownHostException {
		Settings settings = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true)
				.put("client.transport.nodes_sampler_interval", "30s").put("client.transport.ping_timeout", "30s")
				.build();
		TransportClient transportClient = new PreBuiltTransportClient(settings);
		addESNodes(transportClient);
		logger.info("初始化完成");
		return transportClient;
	}

	/**
	 * 添加ES节点
	 * 
	 * @param client
	 * @param esHosts
	 * @throws UnknownHostException
	 */
	private void addESNodes(TransportClient transportClient) throws UnknownHostException {
		if (StringUtils.isBlank(nodes))
			return;
		// 目前是单一节点
		for (String node : nodes.split(",")) {
			if (StringUtils.isNotBlank(node))
				transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(node), port));
		}
	}
}
